#include "touchevent.h"

ts_event * init_touch(const char *device)
{
	ts_event *et = (ts_event *)malloc(sizeof(ts_event));
	const char *touchdev = getenv("TSFEV");
	if(touchdev == NULL)
	{
		touchdev = device;
	}
	et->fd = open(touchdev, O_RDONLY);
	if(et->fd < 0)	
	{
		perror("open fail");
		free(et);
		return NULL;
	}
	return et;
}
	
void get_event(ts_event *et)
{
	struct input_event esmp;
	while(1)
	{
		int ret = read(et->fd, &esmp, sizeof(esmp));
		if(ret < 0)
		{
			perror("read touch fial");
			close(et->fd);
			et->fd = -1;
			return ;
		}
		if(esmp.type == EV_ABS)  //触摸屏
		{
			if(esmp.code == ABS_X)
			{
				et->x = esmp.value;
			}
			else if(esmp.code == ABS_Y)
			{
				et->y = esmp.value;
			}
			else if(esmp.code == ABS_PRESSURE)   // 压力测试即是否有点击   
			{
				if(esmp.value == 0)
					break;	
			}
		}else if(esmp.type == EV_KEY && esmp.code == BTN_TOUCH)  //虚拟键盘触摸事件
		{
			if(esmp.value == 0)
				break;
		}
	}
}
bool exit_touch(ts_event *et)
{
	if(et == NULL)
		return false;
	if(et->fd > 0)
	{
		close(et->fd);
	}
	free(et);
	return true;
}









int main(void)
{
	ts_event *a = malloc(sizeof(ts_event));
	memset(a, 0, sizeof(a));
	a = init_touch("/dev/input/event0");
	//读取触摸屏数据
	while(1)
	{
		get_event(a);
		printf("x=%d, y=%d\n", a->x, a->y);
	}
	exit_touch(a);
	return 0;
}

